<?php
import('miho.controller.Controller');
import('miho.controller.event.ActionControllerEvent');
/**
* FrontController
*/
class FrontController
{
  
  // PROTECTED
  protected static $_instance;
  
  protected $_request;
  public function setRequest($request){
  	$this->_request = $request;
  }
  public function getRequest(){
  	return $this->_request;
  }
    
  protected $_router;
  public function setRouter($router){
  	$this->_router = $router;
  }
  public function getRouter(){
  	return $this->_router;
  }
  
  protected $_application;
  
  
  protected function __construct()
  {
    
  }
  // PUBLIC 
  public static function getInstance(){
    if(self::$_instance==null){
      self::$_instance= new FrontController();
    }
    return self::$_instance;
  }
    
  public function dispatch(){
    $this->_router->route($this->getRequest());
    
    $controller = Controller::getInstance();
    $controller->setApplication($this->_router->getParameter("application"));
    
    
    
    //$controller = ucfirst($this->getRouter()->getParameter('controller')).'Controller';
    
    $action = $this->_router->getParameter('action');
    if($action==null){
      $action = 'index';
    }
    
    
    
    $this->_application = $this->_router->getParameter("application");
    
    // POST_EXECUTE event dispatched only once on last forwarded action. 
    Controller::getInstance()->addEventListener(ActionControllerEvent::POST_EXECUTE,new EventListener($this,"postDispatchHandler"));
    
    /*import($this->_application.'.controller.'.$controller);
    $c = new $controller;
    $c->execute($action);*/
    
    $controller->executeAction(
	    	$this->getRouter()->getParameter('controller'),	
	    	$action
    	);
    
    
        
  }
  
  public function postDispatchHandler($event){
    $vars =$event->getController()->getVars();
    $controller = $event->getController();
    $action = $event->getActionName();
    $app = Controller::getInstance()->getApplication();
    $script = $app.'/view/scripts/'.$controller->getName().$app.ucfirst($action).ucfirst($event->getExecuteResult());
    //var_dump($script);
    View::getInstance()->setLayoutPath($app.'/view/scripts/layout');
    echo (View::getInstance()->render($script,$vars));
  }
}